<?php


namespace app\admin\controller;


use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\AuthRule;
use app\BaseController;
use fast\Tree;
use think\facade\Session;
use think\facade\View;
use think\Request;

class Group extends BaseController
{
    //当前登录管理员所有子组别
    protected $childrenGroupIds = [];
    //当前组别列表数据
    protected $groupdata = [];
    //无需要权限判断的方法
    protected $noNeedRight = ['roletree'];

    public function initialize()
    {
        parent::initialize();
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        $result = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        } else {
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {

                $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
            }
        }

        $groupName = [];
        foreach ($result as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
        $this->groupdata = $groupName;
        View::assign('groupdata', $this->groupdata);
    }

    public function index(Request $request)
    {
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $list = AuthGroup::select();

            $list = collection($list)->toArray();

            $groupList = [];
            foreach ($list as $k => $v) {
                $groupList[$v['id']] = $v;
            }

            $list = [];
            foreach ($this->groupdata as $k => $v) {

                if (isset($groupList[$k])) {
                    $groupList[$k]['name'] = $v;
                    $list[] = $groupList[$k];
                }
            }

            $total = count($list);
//       $result = AuthGroup::paginate($limit, false, ['page' => $page])->toArray();
            return json(['code' => 200, 'msg' => '', 'count' => $total, 'data' => $list]);
        }
        return View::fetch();
    }

    //角色下拉菜单
    public function select()
    {
        $res = AuthGroup::field('id,id as value,name,pid as parent_id,status')->where(['status' => 1])->select();

        $result = toChildren($res, 'list');
        $data = [
            'code' => 0,
            'msg' => "获取成功",
            'trees' => $result
        ];
        return json($data);
    }

    //权限下拉菜单
    public function ruleSelect()
    {
        $res = AuthRule::field('id,id as value,title as name,parent_id,status')->where(['status' => 1])->select();
        $result = toChildren($res, 'list');

        $data = [
            'code' => 0,
            'msg' => "获取成功",
            'trees' => $result
        ];
        return json($data);
    }

    //新增
    public function add(Request $request)
    {
        if ($request->isAjax()) {
            $group = new AuthGroup();

            $params = $request->param();
            if (!isset($params['ids'])) {
                return json(['code' => 400, 'url' => '', 'msg' => '请选择权限！']);
            }
            $parentmodel = AuthGroup::find($params['parent_id']); //查找父组
            if (!$parentmodel) {
                abort(404, '父组别未找到');
            }
            // 父级别的规则节点
            $parentrules = explode(',', $parentmodel->rules);
            // 当前组别的规则节点
            $currentrules = $this->auth->getRuleIds();
            $rules = $params['ids'];
            // 如果父组不是超级管理员则需要过滤规则节点,不能超过父组别的权限
            $rules = in_array('*', $parentrules) ? $rules : array_intersect($parentrules, $rules);
            // 如果当前组别不是超级管理员则需要过滤规则节点,不能超当前组别的权限
            $rules = in_array('*', $currentrules) ? $rules : array_intersect($currentrules, $rules);
            $params['rules'] = implode(',', $rules);
            $params['pid'] = $params['parent_id'];
            $params['level'] = $parentmodel['level'] + 1;
            if ($params) {
                $group->save($params);
                return json(['code' => 200, 'url' => '', 'msg' => '添加成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '添加失败！']);
        }
        return View::fetch();
    }

    //编辑
    public function edit(Request $request, $id)
    {
        $model = AuthGroup::find($id);
        if ($request->isAjax()) {
            $params = $request->param();

            // 父节点不能是它自身的子节点
            if (!in_array($params['pid'], $this->childrenGroupIds)) {
                $this->error(('The parent group can not be its own child'));
            }
            $parentmodel = AuthGroup::find($params['pid']);
            if (!$parentmodel) {
                $this->error(('The parent group can not found'));
            }
            // 父级别的规则节点
            $parentrules = explode(',', $parentmodel->rules);

            $currentrules = $this->auth->getRuleIds();
            $rules = $params['rules'];
            // 如果父组不是超级管理员则需要过滤规则节点,不能超过父组别的权限
            $rules = in_array('*', $parentrules) ? $rules : array_intersect($parentrules, $rules);
            // 如果当前组别不是超级管理员则需要过滤规则节点,不能超当前组别的权限
            $rules = in_array('*', $currentrules) ? $rules : array_intersect($currentrules, $rules);
            $params['rules'] = implode(',', $rules);
            if ($params) {
                AuthGroup::update($params);
                return json(['code' => 200, 'url' => '', 'msg' => '更新成功！']);
            }
            return json(['code' => 400, 'url' => '', 'msg' => '更新失败！']);
        }
        View::assign('id', $id);
        View::assign('pid', $model->pid);
        View::assign('model', $model);
        return View::fetch('edit');
    }

    //获取菜单
    public function ruleSelectTree(Request $request)
    {
        $id = $this->request->param("id");
        $pid = $this->request->param("pid");

        $parentGroupModel = AuthGroup::find($pid);
        $currentGroupModel = null;
        if ($id) {
            $currentGroupModel = AuthGroup::find($id);
        }

        if (($pid || $parentGroupModel) && (!$id || $currentGroupModel)) {
            $id = $id ? $id : null;
            $ruleList = collection(AuthRule::field('id,name,title,parent_id as pid,icon,ismenu,status,sort_order')->order('sort_order', 'asc')->order('id', 'asc')->where('status', 1)->select())->toArray();
            //读取父类角色所有节点列表
            $parentRuleList = [];
            if (in_array('*', explode(',', $parentGroupModel->rules))) {
                $parentRuleList = $ruleList;
            } else {
                $parentRuleIds = explode(',', $parentGroupModel->rules);
                foreach ($ruleList as $k => $v) {
                    if (in_array($v['id'], $parentRuleIds)) {
                        $parentRuleList[] = $v;
                    }
                }
            }

            $ruleTree = new Tree();
            $groupTree = new Tree();
            //当前所有正常规则列表
            $ruleTree->init($parentRuleList);

            //角色组列表
            $groupTree->init(collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray());

            //读取当前角色下规则ID集合
            $adminRuleIds = $this->auth->getRuleIds();
            //是否是超级管理员
            $superadmin = $this->auth->isSuperAdmin();
            //当前拥有的规则ID集合
            $currentRuleIds = $id ? explode(',', $currentGroupModel->rules) : [];
            if (!$id || !in_array($pid, $this->childrenGroupIds) || !in_array($pid, $groupTree->getChildrenIds($id, true))) {
                $parentRuleList = $ruleTree->getTreeList($ruleTree->getTreeArray(0), 'name');
                $hasChildrens = [];
                foreach ($parentRuleList as $k => $v) {
                    if ($v['haschild']) {
                        $hasChildrens[] = $v['id'];
                    }
                }
                $parentRuleIds = array_map(function ($item) {
                    return $item['id'];
                }, $parentRuleList);
                $nodeList = [];
                foreach ($parentRuleList as $k => $v) {
                    if (!$superadmin && !in_array($v['id'], $adminRuleIds)) {
                        continue;
                    }
                    if ($v['pid'] && !in_array($v['pid'], $parentRuleIds)) {
                        continue;
                    }
//                    $state = in_array($v['id'], $currentRuleIds) && !in_array($v['id'], $hasChildrens);
                    $state = in_array($v['id'], $currentRuleIds);
                    $nodeList[] = array('value' => $v['id'], 'id' => $v['id'], 'parent_id' => $v['pid'] ? $v['pid'] : '0', 'name' => ($v['title']), 'type' => 'menu', 'checked' => $state);
                }
                $result = toChildren($nodeList, 'list');
                $data = [
                    'code' => 0,
                    'msg' => "获取成功",
                    'trees' => $result
                ];
                return json($data);
            } else {
                $this->error(('Can not change the parent to child'));
            }
        }
    }


    //删除角色
    public function del($ids = "")
    {
        if ($ids) {
            $ids = explode(',', $ids);
            $grouplist = collection($this->auth->getGroups())->toArray(); //对象转数组
            $group_ids = array_map(function ($group) {
                return $group['id'];
            }, $grouplist);
            // 移除掉当前管理员所在组别
            $ids = array_diff($ids, $group_ids);

            // 循环判断每一个组别是否可删除
            $grouplist = AuthGroup::where('id', 'in', $ids)->select();

            foreach ($grouplist as $k => $v) {
                // 当前组别下有管理员
                $groupone = AuthGroupAccess::where(['group_id' => $v['id']])->find();
                if ($groupone) {
                    $ids = array_diff($ids, [$v['id']]);
                    continue;
                }
                // 当前组别下有子组别
                $groupone = AuthGroup::where(['pid' => $v['id']])->find();
                if ($groupone) {
                    $ids = array_diff($ids, [$v['id']]);
                    continue;
                }
            }
            if (!$ids) {
                return json(['code' => 400, 'url' => '', 'msg' => '你不能删除含有子组和管理员的组！']);
            }
            $count = AuthGroup::destroy(array_values($ids));
            if ($count) {
                return json(['code' => 200, 'url' => '', 'msg' => '删除成功！']);
            }
        }
        return json(['code' => 400, 'url' => '', 'msg' => '参数为空！']);
    }


}